<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

class PropertiesControllerProperty extends PropertiesController
{
	function __construct()
	{
		parent::__construct();
		$this->registerTask( 'apply',	'save' );
		$this->TableName = JRequest::getCmd('table');
	}

	/* save a record (and redirect to main page)	 */
	function save()
	{
		jimport('joomla.filesystem.folder');
		$this->TableName = JRequest::getVar('table');
		$model = $this->getModel('property');

		$post = JRequest::get( 'post' );
		

		if(($this->TableName=='archivos') | ($this->TableName=='products') | ($this->TableName=='profiles')){
			$db 	=& JFactory::getDBO();
			require_once(JPATH_SITE.DS.'configuration.php');
			$datos = new JConfig();
			$basedatos = $datos->db;

			if($this->TableName=='products'){
				$query = "SHOW TABLE STATUS FROM ".$basedatos." LIKE 'jos_properties_products';";
				$db->setQuery( $query );
				$nextAutoIndex = $db->loadObject();
				$destino_imagen = JPATH_SITE.DS.'images'.DS.'properties'.DS;
			}
			if($this->TableName=='archivos'){
				$query = "SHOW TABLE STATUS FROM ".$basedatos." LIKE 'jos_properties_archivos';";
				$db->setQuery( $query );
				$nextAutoIndex = $db->loadObject();
				$destino_imagen = JPATH_SITE.DS.'images'.DS.'properties'.DS.'archivos'.DS;
			}
			if($this->TableName=='profiles'){
				$query = "SHOW TABLE STATUS FROM ".$basedatos." LIKE 'jos_properties_profiles';";
				$db->setQuery( $query );
				$nextAutoIndex = $db->loadObject();
				$destino_imagen = JPATH_SITE.DS.'images'.DS.'properties'.DS.'profiles'.DS;
			}
			if(JRequest::getCmd('id')){ $id_imagen = JRequest::getCmd('id');}
			else{$id_imagen = $nextAutoIndex->Auto_increment;}

			$description2 = JRequest::getVar( 'description2', '', 'post', 'string', JREQUEST_ALLOWRAW );
			// Clean text for xhtml transitional compliance
			$description2		= str_replace( '<br>', '<br />', $description2 );
			$post['description2'] = $description2;
			//$contenido .=	'$post[descripcion2_producto: '.$post['descripcion2_producto']."\n";
			//$contenido .=	utf8_decode($post['descripcion2_producto'])."\n";
			//fwrite($gestor, $contenido);
			if (isset($_FILES['archivofisico'])){
				//if (JRequest::getVar('archivofisico')){
				$destino_archivo = JPATH_SITE.DS.'images'.DS.'properties'.DS.'archivos'.DS;
				move_uploaded_file($_FILES['archivofisico']['tmp_name'],	$destino_archivo.$id_imagen.'_'.$_FILES['archivofisico']['name']);

				$post['archivofisico'] = $destino_archivo.$id_imagen.'_'.$_FILES['archivofisico']['name'];
				$ruta= JURI::root().'images/properties/archivos/'.$id_imagen.'_'.$_FILES['archivofisico']['name'];
				$post['ruta'] = $ruta;
				//$contenido = '<br>existe<br>';
			}
			/*
			 $nombre_archivo = 'components\com_properties\fabio_archivofisico.txt';
			 $gestor = fopen($nombre_archivo, 'w');
			 $contenido .= '<br>tmp_name: '.$_FILES['archivofisico']['tmp_name'];
			 $contenido .= '<br>JRequest::getVar(archivofisico): '.JRequest::getVar('archivofisico').'<br>';
			 $contenido .= '$id_imagen: '.$id_imagen.'_0'.'.jpg';
			 $contenido .= '<br>destino_archivo: '.$destino_archivo;
			 $contenido .= '<br>ruta: '.$destino_archivo.$id_imagen.'_0.jpg';
			 $contenido .= '<br>'.$post['archivofisico'].'<br>';

			 $nombre_archivo1 = 'components\com_properties\fabio_archivo.txt';
			 $gestor1 = fopen($nombre_archivo1, 'w');
			 $contenido1 .= '<br>'.$this->TableName;
			 */
			if (isset($_FILES['panoramic'])){
				$destino_panoramic = JPATH_SITE.DS.'images'.DS.'properties'.DS.'panoramics'.DS;
				move_uploaded_file($_FILES['panoramic']['tmp_name'],	$destino_panoramic.$id_imagen.'_0.jpg');
				$post['panoramic'] = $id_imagen.'_0'.'.jpg';
			}

			if (isset($_FILES['image'])){

				$typeimg = $_FILES['image']['type'];
				if (!empty($typeimg)) {
					if($typeimg == 'image/jpeg'){$ext='.jpg';}else{$ext= '.'.substr($typeimg, strlen($typeimg) - 3); }
					$personal_image = JPATH_SITE.DS.'images'.DS.'properties'.DS.'profiles'.DS;
					move_uploaded_file($_FILES['image']['tmp_name'],	$personal_image.$id_imagen.'_p'.$ext);
					$post['image'] = $id_imagen.'_p'.$ext;
					$AnchoLogo=140;
					$AltoLogo=200;
					$destinoCopia=$personal_image;
					$destinoNombre=$post['image'];
					$destino = $personal_image;
					$this->CambiarTamanoExacto($post['image'],$AnchoLogo,$AltoLogo,$destinoCopia,$destinoNombre,$destino);

				}
			}

			if (isset($_FILES['logo_image'])){

				$typeimg = $_FILES['logo_image']['type'];
				if (!empty($typeimg)) {
					if($typeimg == 'image/jpeg'){$ext='.jpg';}else{$ext= '.'.substr($typeimg, strlen($typeimg) - 3); }
					$personal_image = JPATH_SITE.DS.'images'.DS.'properties'.DS.'profiles'.DS;
					move_uploaded_file($_FILES['logo_image']['tmp_name'],	$personal_image.$id_imagen.'_l'.$ext);
					$post['logo_image'] = $id_imagen.'_l'.$ext;
					$AnchoLogo=140;
					$AltoLogo=45;
					$destinoCopia=$personal_image;
					$destinoNombre=$post['logo_image'];
					$destino = $personal_image;
					$this->CambiarTamanoExacto($post['logo_image'],$AnchoLogo,$AltoLogo,$destinoCopia,$destinoNombre,$destino);

				}
			}
			if (isset($_FILES['logo_image_large'])){

				$typeimg = $_FILES['logo_image_large']['type'];
				if (!empty($typeimg)) {
					if($typeimg == 'image/jpeg'){$ext='.jpg';}else{$ext= '.'.substr($typeimg, strlen($typeimg) - 3); }
					$personal_image = JPATH_SITE.DS.'images'.DS.'properties'.DS.'profiles'.DS;
					move_uploaded_file($_FILES['logo_image_large']['tmp_name'],	$personal_image.$id_imagen.'_ll'.$ext);
					$post['logo_image_large'] = $id_imagen.'_ll'.$ext;
					$AnchoLogo=500;
					$AltoLogo=160;
					$destinoCopia=$personal_image;
					$destinoNombre=$post['logo_image_large'];
					$destino = $personal_image;
					$this->CambiarTamanoExacto($post['logo_image_large'],$AnchoLogo,$AltoLogo,$destinoCopia,$destinoNombre,$destino);
				}
			}
			/*fwrite($gestor1, $contenido1);*/
			/*
			 if (isset($_FILES['imagen1_producto'])){
			 move_uploaded_file($_FILES['imagen1_producto']['tmp_name'],	$destino_imagen.$id_imagen.'_0.jpg');
			 $post['imagen0_producto'] = $id_imagen.'_0'.'.jpg';
			 $this->CambiarTamano($post['imagen1_producto'],640,480,$destino_imagen,$post['imagen1_producto']);
			 $this->CambiarTamano($post['imagen1_producto'],100,100,$destino_imagen."peques".DS,'peque_'.$id_imagen.'_0'.'.jpg');
			 }
			 */
			if (isset($_FILES['files'])){
				$component = JComponentHelper::getComponent( 'com_properties' );
				$params = new JParameter( $component->params );
				$AnchoMiniatura=$params->get('AnchoMiniatura');
				$AltoMiniatura=$params->get('AltoMiniatura');
				$AnchoImagen=$params->get('AnchoImagen');
				$AltoImagen=$params->get('AltoImagen');
				$i=1;
				for($i=1;$i<25;$i++) {
					$name = $_FILES['files']['name'][$i];
					if (!empty($name)) {
						$totalImagenes++;
						$nombreImagen[$i]=$_FILES['files']['name'] [$i];

						$typeimg = $_FILES['files']['type'] [$i];
						echo 'type: '.$typeimg;
						if($typeimg == 'image/jpeg'){$ext='.jpg';}else{$ext= '.'.substr($typeimg, strlen($typeimg) - 3); }
						echo '  $ext  '.$ext;
						$post['image'.($i)] = $id_imagen.'_'.($i).$ext;

						move_uploaded_file($_FILES['files']['tmp_name'] [$i], $destino_imagen.$id_imagen.'_'.($i).$ext);
						@chmod($destino_imagen.$id_imagen.'_'.($i).$ext, 0666);

						$destino = JPATH_SITE.DS.'images'.DS.'properties'.DS;
						$destinoCopia=$destino_imagen."peques".DS;
						$destinoNombre='peque_'.$id_imagen.'_'.($i).$ext;
						$this->CambiarTamano($id_imagen.'_'.($i).$ext,$AnchoMiniatura,$AltoMiniatura,$destinoCopia,$destinoNombre,$destino);
						$this->CambiarTamano($id_imagen.'_'.($i).$ext,$AnchoImagen,$AltoImagen,$destino_imagen,$id_imagen.'_'.($i).$ext,$destino);


					}
				}
			}
			
			
			
			//thuan add 27-08-09
			if (!empty($_FILES['video']['name'])){
//				if(!empty(JRequest::getCmd('id')))
//				{
//					$product = $model->getProduct();
//					@unlink($destino_imagen.$id_imagen.'_'.$product->video);
//				}
				if(!move_uploaded_file($_FILES['video']['tmp_name'], $destino_imagen.$id_imagen.'_'.$_FILES['video']['name']))
				{
					echo "error upload file";exit;
				}
				$post['video'] = $id_imagen.'_'.$_FILES['video']['name'];
			}
			else
			{
				$post['video'] = $post['video_edit'];
			}
			
			
			//thuan end
		}



		//echo 	$this->TableName;

		

		if ($model->store($post,$this->TableName)) {
			$LastModif = $model->getLastModif();
			if($this->TableName=='products'){
				if ($model->storeProductCategory($post,$LastModif)) {
					$msg1='';
				}
			}

			print_r($post);

			if(JRequest::getCmd('id')){ $id = JRequest::getCmd('id');}
			else{$id = $LastModif;}

			$nombre_archivo1 = 'components\com_properties\fabio_aply.txt';
			$gestor1 = fopen($nombre_archivo1, 'w');
			$contenido1 .= '<br>'.$id;
			$contenido1 .= '<br>'.$LastModif;
			fwrite($gestor1, $contenido1);

			//$table	=& JTable::getInstance($this->TableName, 'Table');
			$msg=JText::_('Saved  '.$this->TableName);



			$link = JRoute::_('index.php?option=com_properties&view=panel&task=edit&id='.$id,false);
			$this->setRedirect($link, $msg);



			$this->setMessage( JText::_( $msg ) );


			//	$msg = JText::_( 'Guardado '.$this->TableName.' : '.$cid.'!!!');
			// Check the table in so it can be edited.... we are done with it anyway
			//$link = 'index.php?option=com_gestor&Tabla='.$this->TableName;
			//$this->setRedirect($link, $msg);

		} else {
			$msg = JText::_( 'Error Saving Greeting' );
			$msg .=  'err'.$this->Err;
		}


	}

	/** remove record(s)	 */
	function remove()
	{
		$this->TableName = JRequest::getCmd('table');
		$model = $this->getModel('property');
		if(!$model->delete()) {
			$msg = JText::_( 'Error: One or More Greetings Could not be Deleted' );
		} else {
			$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
			foreach($cids as $cid) {

				$msg .= JText::_( 'Deleted '.$this->TableName );
					
			}
		}

		$this->setRedirect( 'index.php?option=com_properties&table='.$this->TableName, $msg );
	}

	/**	 * cancel editing a record */
	function cancel()
	{
		$this->TableName = JRequest::getCmd('table');
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_properties&table='.$this->TableName, $msg );
	}



	/** remove record(s)	 */
	function delimg()
	{
		$this->TableName = JRequest::getCmd('table');
		$campo =  'image'.JRequest::getVar('borrar');
		$model = $this->getModel('property');
		if(!$model->deleteimg()) {
			$msg = JText::_( 'Error: One or More Greetings Could not be Deleted' );
		} else {
			$id = JRequest::getVar('id');
			$msg .= JText::_( 'Image Deleted' );
				
		}

		$this->setRedirect( 'index.php?option=com_properties&controller=property&table='.$this->TableName.'&task=edit&cid[]='.$id, $msg );
		//echo 'borar'.JRequest::getVar('borrar');
		//echo '<br>id:'.JRequest::getVar('id');
	}




	function CambiarTamano($nombre,$max_width,$max_height,$destinoCopia,$destinoNombre,$destino)
	{

		/*
		 $InfoImage=getimagesize($destino.$nombre);
		 $width=$InfoImage[0];
		 $height=$InfoImage[1];
		 $type=$InfoImage[2];

		 $x_ratio = $max_width / $width;
		 $y_ratio = $max_height / $height;

		 if (($width <= $max_width) && ($height <= $max_height) ) {
		 $tn_width = $width;
		 $tn_height = $height;
		 } else if (($x_ratio * $height) < $max_height) {
		 $tn_height = ceil($x_ratio * $height);
		 $tn_width = $max_width;
		 } else {
		 $tn_width = ceil($y_ratio * $width);
		 $tn_height = $max_height;
		 }
		 $width=$tn_width;
		 $height	=$tn_height;
		 */





		$InfoImage=getimagesize($destino.$nombre);
		$width=$InfoImage[0];
		$height=$InfoImage[1];
		$type=$InfoImage[2];
		$max_height = $max_width;

		$x_ratio = $max_width / $width;
		$y_ratio = $max_height / $height;

		if (($x_ratio * $height) < $max_height) {
			$tn_height = ceil($x_ratio * $height);
			$tn_width = $max_width;
		} else {
			$tn_width = ceil($y_ratio * $width);
			$tn_height = $max_height;
		}
		$width=$tn_width;
		$height	=$tn_height;



			
		switch($type)
		{
			case 1: //gif
				{
					$img = imagecreatefromgif($destino.$nombre);
					$thumb = imagecreatetruecolor($width,$height);
					imagecopyresampled($thumb,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
					ImageGIF($thumb,$destinoCopia.$destinoNombre,100);

					break;
				}
			case 2: //jpg,jpeg
				{
					$img = imagecreatefromjpeg($destino.$nombre);
					$thumb = imagecreatetruecolor($width,$height);
					imagecopyresampled($thumb,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
					ImageJPEG($thumb,$destinoCopia.$destinoNombre);
					break;
				}
			case 3: //png
				{
					$img = imagecreatefrompng($destino.$nombre);
					$thumb = imagecreatetruecolor($width,$height);
					imagecopyresampled($thumb,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
					ImagePNG($thumb,$destinoCopia.$destinoNombre);
					break;
				}
		} // switch

	}




	function CambiarTamanoExacto($nombre,$max_width,$max_height,$destinoCopia,$destinoNombre,$destino)
	{


		$InfoImage=getimagesize($destino.$nombre);
		$width=$InfoImage[0];
		$height=$InfoImage[1];
		$type=$InfoImage[2];

		$x_ratio = $max_width / $width;
		$y_ratio = $max_height / $height;

		if (($width <= $max_width) && ($height <= $max_height) ) {
			$tn_width = $width;
			$tn_height = $height;
		} else if (($x_ratio * $height) < $max_height) {
			$tn_height = ceil($x_ratio * $height);
			$tn_width = $max_width;
		} else {
			$tn_width = ceil($y_ratio * $width);
			$tn_height = $max_height;
		}
		$width=$tn_width;
		$height	=$tn_height;

			
		switch($type)
		{
			case 1: //gif
				{
					$img = imagecreatefromgif($destino.$nombre);
					$thumb = imagecreatetruecolor($width,$height);
					imagecopyresampled($thumb,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
					ImageGIF($thumb,$destinoCopia.$destinoNombre,100);

					break;
				}
			case 2: //jpg,jpeg
				{
					$img = imagecreatefromjpeg($destino.$nombre);
					$thumb = imagecreatetruecolor($width,$height);
					imagecopyresampled($thumb,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
					ImageJPEG($thumb,$destinoCopia.$destinoNombre);
					break;
				}
			case 3: //png
				{
					$img = imagecreatefrompng($destino.$nombre);
					$thumb = imagecreatetruecolor($width,$height);
					imagecopyresampled($thumb,$img,0,0,0,0,$width,$height,imagesx($img),imagesy($img));
					ImagePNG($thumb,$destinoCopia.$destinoNombre);
					break;
				}
		} // switch

	}




}